package com.xzcs.util.common;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GsonUtils {

	/**
	 * json字符转map
	 * @param jsonData
	 * @return
     */
	public static Map<String, Object> parseStringMap(String jsonData) {
		Type mapType = new TypeToken<Map<String, String>>(){}.getType();
		Gson gson = new Gson();
		Map map = gson.fromJson(jsonData, mapType);
		return map;
	}

	public static Map<?, ?> stringToMap(String jsonData) {
		try{
			Type mapType = new TypeToken<Map<?, ?>>(){}.getType();
			Gson gson = new Gson();
			Map<?, ?> map = gson.fromJson(jsonData, mapType);
			if(map == null) {
				return new HashMap();
			}
			return map;
		}catch (Exception e) {
			e.printStackTrace();
		}
		return new HashMap();
	}

	/**
	 * json字符转list
	 * @param jsonData
	 * @return
     */
	public static List<Map<String, Object>> parseMapList(String jsonData) {
		Type mapType = new TypeToken<List<Map<String, Object>>>(){}.getType();
		Gson gson = new Gson();
		List list = gson.fromJson(jsonData, mapType);
		return list;
	}

	/**
	 * list转字符
	 * @param list
	 * @return
     */
	public static String list2Json(List<Map<String, Object>> list) {
		Gson gson = new Gson();
		String result = gson.toJson(list);
		return result;
	}

	/**
	 * map转字符
	 * @param map
	 * @return
     */
	public static String map2Json(Map<String, Object> map) {
		Gson gson = new Gson();
		String result = gson.toJson(map);
		return result;
	}

	/**
	 * 对象转字符
	 * @param object
	 * @return
     */
	public static String object2Json(Object object) {
		Gson gson = new Gson();
		String result = gson.toJson(object);
		return result;
	}

}
